package com.foreveross.law.workflow.service.impl;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.foreveross.law.common.util.JaxbUtil;
import com.foreveross.law.common.util.XMLUtils;
import com.foreveross.law.workflow.domain.ProcessMessage;
import com.foreveross.law.workflow.domain.RouteResultMessage;
import com.foreveross.law.workflow.domain.RoutesInfo;
import com.foreveross.law.workflow.service.WorkflowService;
import com.foreveross.law.wps.client.GetNewProcessRouteInfo;
import com.foreveross.law.wps.client.GetNewProcessRouteInfoResponse;
import com.foreveross.law.wps.client.NewProcessSubmit;
import com.foreveross.law.wps.client.SubmitWorkqueue;
import com.foreveross.law.wps.service.LawWpsServiceImpl;

@Service
public class WorkflowServiceImpl implements WorkflowService{

	@Override
	public String createWF(String wfAlias, String token, String formData,String workflowName,ProcessMessage processMessage) {
		// TODO Auto-generated method stub
		//1.获取流程路由
		
		//2.根据表单数据选择路由信息
		
		//3.组装流程信息
		
		//4.创建流程
		NewProcessSubmit info = new NewProcessSubmit();
		info.setAlias(wfAlias);
		String formXml = "<Content><FormInfo><__ProcessName__>"+workflowName+"</__ProcessName__>"+XMLUtils.json2xml(formData)+"</FormInfo></Content>";
		System.err.println(formXml);
		info.setFormContent(formXml);
		info.setToken(token);
		info.setXml(JaxbUtil.convertToXml(processMessage));
		System.err.println(JaxbUtil.convertToXml(processMessage));
		String flag = LawWpsServiceImpl.getInstance().createProcess(info).getNewProcessSubmitResult();
		String isOk = "1";
		if(flag.indexOf("成功") != -1){
			isOk = "0";
		}
		JSONObject json = new JSONObject();
		json.put("msg", isOk);
		return json.toJSONString();
	}

	@Override
	public RoutesInfo getCreateNewRoutInfo(String wfAlias, String token) {
		// TODO Auto-generated method stub
		LawWpsServiceImpl client = LawWpsServiceImpl.getInstance();
		GetNewProcessRouteInfo info = new GetNewProcessRouteInfo();
		info.setAlias(wfAlias);
		info.setToken(token);
		GetNewProcessRouteInfoResponse response = client.getNewProcessRouteInfo(info);
		String xml = response.getGetNewProcessRouteInfoResult();
		return JaxbUtil.converyToJavaBean(xml, RouteResultMessage.class).getRoutesInfo();
	}

	@Override
	public String submitWF(String token, ProcessMessage processMessage) {
		// TODO Auto-generated method stub
		SubmitWorkqueue wf = new SubmitWorkqueue();
		wf.setToken(token);
		wf.setXml(JaxbUtil.convertToXml(processMessage));
		String flag = LawWpsServiceImpl.getInstance().submitWorkqueue(wf).getSubmitWorkqueueResult();
		
		String isOk = "1";
		if(flag.indexOf("0") != -1){
			isOk = "0";
		}
		
		JSONObject json = new JSONObject();
		json.put("msg", isOk);
		return json.toJSONString();
	}

	@Override
	public String getWorkToDoList(String token, String type) {
		// TODO Auto-generated method stub
		return null;
	}

}
